package com.lagou.controller;

import com.lagou.common.pojo.Order;
import com.lagou.common.service.OrderService;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private AmqpTemplate rabbitTemplate;

    @GetMapping("/create")
    public Order create(@RequestParam String name, @RequestParam Integer amount) {

        Order order = new Order();
        order.setName(name);
        order.setAmount(amount);
        order.setStatus("paying");
        order.setOrderTime(new Date());
        orderService.save(order);

        System.out.println(order);

        rabbitTemplate.convertAndSend("ex.payment", "key.payment", order);

        return order;
    }

    @GetMapping("/pay")
    public boolean pay(@RequestParam Long orderId) {
        Order order = orderService.findById(orderId);

        // 只有订单状态在正在支付的情况下才能进行支付
        if (order.getStatus().equals("paying")) {
            order.setStatus("finish");
            order.setPayTime(new Date());
            orderService.save(order);

            return true;
        } else {
            return false;
        }

    }

    @GetMapping("/list")
    public List<Order> list(@RequestParam String status) {
        return orderService.findAllByStatus(status);
    }
}
